/*用于从缓存中获取配置的下拉列表*/

function getSelectOptionsWithCode(options){
    var params = $.extend(true, {}, {code:null,selectid:null,disabled:false}, options);
    if(params.code == null || params.code==''|| params.selectid == null){
        layerAlert.errorMessage("参数错误");
        return;
    }
    var jsonArr=[];
    $.ajax({
        type: "get",
        url: projectPath + '/base/constss/list',
        data:{code:params.code},
        dataType: "json",
        success: function (objdata) {
            var result = objdata.data;
            if (result) {
                $.each(result, function (index, item) {
                    var jsona = {
                        name: item.constname,
                        value: item.constvalue,
                        dispno: item.dispno + 1
                    };
                    jsonArr.push(jsona);
                });
            }
            jsonArr =  jsonArr.sort(compare('dispno'));
            $("#"+params.selectid).empty();
            $("#"+params.selectid).append("<option value='' code='' "+(options.disabled?"disabled":"")+">--请选择--</option>");
            $.each(jsonArr, function (index, item) {
                $("#"+params.selectid).append("<option value='"+item.value+"' code='"+params.code+"' "+(options.disabled?"disabled":"")+">"+item.name+"</option>");
            });
            $("#"+params.selectid).selectpicker('refresh');
        },
        error: function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
}

function listOperatorSelect(options){
    var params = $.extend(true, {}, {data:{},selectid:null}, options);
    if(params.selectid == null){
        layerAlert.errorMessage("参数错误");
        return;
    }
    var jsonArr = [];
    $.ajax({
        type: "get",
        url: projectPath + '/sync/operators/list',
        dataType: "json",
        success: function (objdata) {
            var result = objdata.data;
            if (result) {
                $.each(result, function (index, item) {
                    var jsona = {
                        name: item.name,
                        value: item.uuid,
                        code: item.operatorid,
                        dispno: item.type
                    };
                    jsonArr.push(jsona);
                });
            }
            jsonArr =  jsonArr.sort(compare('dispno'));
            $("#"+params.selectid).html('');
            $.each(jsonArr, function (index, item) {
                $("#"+params.selectid).append("<option value='"+item.value+"' code='"+params.code+"'>"+item.name+"</option>");
            });
            $("#"+params.selectid).selectpicker('refresh');
        },
        error: function () {
            layerAlert.errorMessage("不好意思，数据出错啦！");
        }
    });
}

/**
 *
 * @param title 弹框标题
 * @param textid 选择后页面反写input元素id
 * @param level 展示层级约束，为空则标识不限制
 */
function initOrgTreeLayer(status,title,textid,level){
    var jsonArr = getOrgTreeList(status);
    var index = layer.open({
        type:1,
        title:title,
        shade:0.3,
        shadeClose: true,
        move :false,
        area: ['50%', '80%'],
        skin: 'layui-layer-rims',
        content:$(".provinceCityPartJsTree"),
        btn:['选择','取消','清除'],
        fixed:false,
        resize:true,
        maxmin:true,
        success:function(){
            initOrgTree(jsonArr,"jsZtreelayer","search_input",level);
        },
        btn1:function(){
            $("#"+textid).attr("data-id",selectNode.id);
            var ids="";
            var texts = "";
            for(var i = selectNode.parents.length-1;i>=0;i--){
                if(selectNode.parents[i]!="#"){
                    ids+=selectNode.parents[i]+"-";
                    texts += $('#jsZtreelayer').jstree("get_node", selectNode.parents[i]).text+"-";
                }
            }
            $("#"+textid).attr("data-pids",ids+selectNode.id);
            $("#"+textid).val(texts + selectNode.text);
            $.jstree.destroy();
        },
        btn2:function () {
            $.jstree.destroy();
        },
        btn3:function () {
            $("#"+textid).val('');
            $("#"+textid).attr('data-id','');
            $("#"+textid).attr('parants','');
            $.jstree.destroy();
            layer.close(index);
        },
        cancel: function(){
            $.jstree.destroy();
        }
    });
}

//获取选择的树形节点
var selectNode = {text:'',id:''};
function initOrgTree(jsonArr,id,searchtextid,level){
    $("#"+searchtextid).val('');
    var to = false;
    $('#'+searchtextid).keyup(function () {
        if(to) {
            clearTimeout(to);
        };
        to = setTimeout(function () {
            var v = $('#'+searchtextid).val();
            $('#'+id).jstree(true).search(v, false, true);
        }, 300);
    });
    $.ajaxSetup({cache:false});
    $("#"+id).data('jstree', false).empty().jstree({
        ui : {
            theme_name : "redio"
        },
        core:{
            'check_callback' : true,
            'data' : function (obj, callback) {
                if(jsonArr && jsonArr.length > 0 ){
                    callback.call(this,orgLevelLimit(jsonArr,level));
                } else {
                    $("#"+id).html("无数据！");
                }
            },
            "multiple": false
        },
        types : {
            "default" : {
                "icon" : "glyphicon glyphicon-wrench"
            },
            "ptnode" : {
                "icon" : "glyphicon glyphicon-th"
            }
        },
        "plugins" : [
            "contextmenu",
            "dnd",
            "massload",
            "search",
            "sort",
            "state",
            "types",
            "unique",
            "wholerow",
            "changed",
            "conditionalselect"
        ]
    }).on('changed.jstree', function (event, data) {  //绑定的点击事件
        if(data.node){
            selectNode = data.node;
        }
    });
}
//获取所有节点集合
function getOrgTreeList(status){
    var jsonArr = [];
    if(jsonArr.length == 0){
        $.ajax({
            type: "get",
            url:projectPath+'/sync/organizations/getAllList',
            data:{status:status},
            async:false,
            dataType:"json",
            success:function(objdata) {
                debugger;
                var result = objdata.data;
                console.log(result);
                if(result){
                    $.each(result,function (index,item) {
                        var jsona = {
                            id:item.orgno,
                            text:item.name,
                            parent:item.parentorgno=="3"?"#":item.parentorgno,
                            state:{seleted:false},
                            level:item.level
                        };
                        jsonArr.push(jsona);
                    });
                }
            },
            error:function () {
                layerAlert.errorMessage("不好意思，数据出错啦！");
            }
        });
    }
    return jsonArr;
}

function orgLevelLimit(jsonArr,level){
    if(!level){
        return jsonArr;
    }
    var arr = [];
    $.each(jsonArr,function (index,item) {
        if(level && item.level>level) {
            return true;
        }
        arr.push(item);
    });
    return arr;
}

//获取行政区划树形
window.districtArr=[];
function getDistrictTreeList(){
    if(districtArr.length == 0){
        $.ajax({
            type: "get",
            url:projectPath+'/sync/organizations/listUsrDistrictAll',
            async:false,
            dataType:"json",
            success:function(objdata) {
                var result = objdata.data;
                if(result){
                    $.each(result,function (index,item) {
                        var jsona = {
                            id:item.code,
                            text:item.name,
                            parent:item.level=="1"?"#":(item.level=="2"?item.provinceCode:item.cityCode),
                            level:item.level,
                            state:{seleted:false,disabled:item.level=="3"?false:true}
                        };
                        districtArr.push(jsona);
                    });
                }
            },
            error:function () {
                layerAlert.errorMessage("不好意思，数据出错啦！");
            }
        });
    }
}

var selectDistrictNode = {text:'',id:''};
function initDistrictTree(id,searchtextid){
    $("#"+searchtextid).val('');
    var to = false;
    $('#'+searchtextid).keyup(function () {
        if(to) {
            clearTimeout(to);
        };
        to = setTimeout(function () {
            var v = $('#'+searchtextid).val();
            $('#'+id).jstree(true).search(v, false, true);
        }, 300);
    });
    $.ajaxSetup({cache:false});
    $("#"+id).data('jstree', false).empty().jstree({
        ui : {
            theme_name : "redio"
        },
        core:{
            'check_callback' : true,
            'data' : function (obj, callback) {
                if(districtArr && districtArr.length > 0 ){
                    callback.call(this,districtArr);
                } else {
                    $("#"+id).html("无数据！");
                }
            },
            "multiple": false
        },
        types : {
            "default" : {
                "icon" : "glyphicon glyphicon-wrench"
            },
            "ptnode" : {
                "icon" : "glyphicon glyphicon-th"
            }
        },
        "plugins" : [
            "contextmenu",
            "dnd",
            "massload",
            "search",
            "sort",
            "state",
            "types",
            "unique",
            "wholerow",
            "changed",
            "conditionalselect"
        ]
    }).on('changed.jstree', function (event, data) {  //绑定的点击事件
        if(data.node){
            selectDistrictNode = data.node;
        }
    });
}

function initDistrictTreeLayer(title,textid,layerid,searchid){
    getDistrictTreeList();
    var index = layer.open({
        type:1,
        title:title,
        shade:0.3,
        shadeClose: true,
        move :false,
        area: ['50%', '80%'],
        skin: 'layui-layer-rims',
        content:$(".provinceCityPartJsTree"),
        btn:['选择','取消','清除'],
        fixed:false,
        resize:true,
        maxmin:true,
        success:function(){
            initDistrictTree(layerid,searchid);
        },
        btn1:function(){
            var ids="";
            var texts="";
            for(var i = selectDistrictNode.parents.length-1;i>=0;i--){
                if(selectDistrictNode.parents[i]!="#"){
                    ids+=selectDistrictNode.parents[i]+"-";
                    texts += $('#'+layerid).jstree("get_node", selectDistrictNode.parents[i]).text+"-";
                }
            }
            $("#"+textid).val(texts+selectDistrictNode.text);
            $("#"+textid).attr("data-id",ids+selectDistrictNode.id);
            $("#"+textid).attr("data-pids",ids+selectDistrictNode.id);
            $.jstree.destroy();
        },
        btn2:function () {
            $.jstree.destroy();
        },
        btn3:function () {
            $("#"+textid).val('');
            $("#"+textid).attr('data-id','');
            $("#"+textid).attr('parants','');
            $.jstree.destroy();
            layer.close(index);
        },
        cancel: function(){
            $.jstree.destroy();
        }
    });
}



//获取菜单树形
window.menuArr=[];
function getMenuTreeList(){
    if(menuArr.length == 0){
        $.ajax({
            type: "GET",
            url:projectPath+'/base/menus/list',
            async:false,
            dataType:"json",
            success:function(objdata) {
                var result = objdata.data;
                if(result){
                    $.each(result,function (index,item) {
                        var jsona = {
                            id:item.uuid,
                            text:item.name,
                            parent:(item.parentuuid =="" || item.parentuuid ==null)?"#":item.parentuuid,
                            state:{seleted:false}
                        };
                        menuArr.push(jsona);
                    });
                }
            },
            error:function () {
                layerAlert.errorMessage("不好意思，数据出错啦！");
            }
        });
    }
}

/**
 * 初始化菜单树形
 * @param id 弹窗层id
 * @param initflag 是否对比选中标记
 * @param initarr 对比选中数组
 */
function initMenuTree(id,initflag,initarr){
    getMenuTreeList();

    $.ajaxSetup({cache:false});
    $("#"+id).data('jstree', false).empty().jstree({
        ui : {
            theme_name : "checkbox"
        },
        core:{
            'check_callback' : true,
            'data' : function (obj, callback) {
                if(menuArr && menuArr.length > 0 ){
                    callback.call(this,menuArr);
                } else {
                    $("#"+id).html("无数据！");
                }
            },
            "multiple": true
        },
        types : {
            "default" : {
                "icon" : "glyphicon glyphicon-wrench"
            },
            "ptnode" : {
                "icon" : "glyphicon glyphicon-th"
            }
        },
        "plugins" : [
            "checkbox",
            "contextmenu",
            "massload",
            "search",
            "sort",
            "types",
            "wholerow",
            "changed",
            "conditionalselect"
        ]
    }).on('loaded.jstree', function (e, data) {
        if(initflag==true && initarr && initarr.length>0){
            for (var index in initarr) {
                $("#"+id).jstree('select_node', initarr[index].uuid, true);
            }
        }
    });

    $("#"+id).jstree(true).get_all_checked = function(full) {
        var tmp=new Array;
        for(var i in this._model.data){
            if((this.is_undetermined(i)||this.is_checked(i)) && this._model.data[i].id!='#' ){tmp.push(full?this._model.data[i]:i);}
        }
        return tmp;
    };
}

function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}